package com.hospital.common.config;

import com.hospital.common.utils.PropertiesLoader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

/**
 * 跨域配置
 * <br>如果需要导入跨域配置,请在启动类使用@Import注解导入
 * @author yhn
 * @version 1.0
 */
@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        // 获取配置信息
        Properties corsProperties = PropertiesLoader.load("cors.properties");
        //1. 添加 CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //放行哪些原始域
        config.setAllowedOrigins(Arrays.stream(corsProperties.getProperty("cors.allowOrigins").split( ",")).toList());
        //放行哪些请求方式
        config.setAllowedMethods(Arrays.stream(corsProperties.getProperty("cors.allowMethods").split( ",")).toList());
        //放行哪些原始请求头部信息
        config.setAllowedHeaders(Arrays.stream(corsProperties.getProperty("cors.allowHeaders").split( ",")).toList());
        //暴露哪些头部信息
        config.setExposedHeaders(Arrays.stream(corsProperties.getProperty("cors.exposedHeaders").split( ",")).toList());
        //设置预检请求的缓存时间（秒）,即在这个时间段里,对于相同地跨域请求不会再预检了
        config.setMaxAge(Duration.ofSeconds(Long.parseLong(corsProperties.getProperty("cors.maxAge"))));
        //2. 添加映射路径
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**",config);
        //3. 返回新的CorsFilter
        return new CorsFilter(corsConfigurationSource);
     }
}
